package com.restaurant.application.root;

import com.nebutown.base.ViewSpec;
import com.nebutown.base.data.View;
import com.nebutown.generation.basictype.UID;
import com.restaurant.application.cashierfacade.CashierFacade;
import com.restaurant.application.genshanguser.GenShangUser;
import com.restaurant.application.indexes.genshanguserList.mysql.GenShangUserListBean;
import com.restaurant.application.indexes.genshanguserList.mysql.GenShangUserListCriteria;
import com.restaurant.application.indexes.genshanguserList.mysql.GenShangUserListImpl;
import com.restaurant.application.login.Login;
import com.restaurant.application.minifacade.MiniFacade;
import com.restaurant.application.root.support.AbstractRoot;

import java.util.List;

public class RootImpl extends AbstractRoot {

    @Override
    public View getFullView() {
        initAdminUser();
        trimTree();

        if (getGate() != null) {
            return getUnit(getUnit(GenShangUser.class, getGate()).getDesktop(false)).getFullView().withDockIn("PageRoot");
        }
        ClientTypeEnum type = ClientTypeEnum.ADMIN;
        try {
            type = ClientTypeEnum.valueOf(getClientType());
        } catch (Throwable rt) {
            getLogger().error("Undefined clientType for session found: " + getClientType());
        }
        switch (type) {
            case MINIAPP:
                return getSingleton(MiniFacade.class).getFullView().withDockIn("PageRoot");
            case CASHIER:
                return getSingleton(CashierFacade.class).getFullView().withDockIn("PageRoot");
            default:
                return getSingleton(Login.class).getFullView().withDockIn("PageRoot");
        }
    }

    private void initAdminUser() {
        GenShangUserListCriteria criteria = new GenShangUserListCriteria().withNickNameEquals("admin");
        List<GenShangUserListBean> beans = getIndex(GenShangUserListImpl.class).search(criteria, null, 1);
        if (beans.size() > 0) {
            createNode(GenShangUser.class).asFirstUser();
            quickIndexUpdate();
        }
    }

    @Override
    public View getViewLead(ViewSpec spec) {
        return null;
    }

    @Override
    public void takeGuest(UID uid) {
        addToRequestCache("view", uid.value());
    }

    @Override
    public void removeGuest(UID uid) {
        addToRequestCache("view", uid.value());
    }

    @Override
    public void logout(View view) {
        getTop().logout(view);
    }
}
